package com.angel.bo.admin.service.impl;

import com.angel.bo.admin.mapper.MenuMapper;
import com.angel.bo.admin.service.MenuService;
import com.angel.bo.beans.admin.dto.MenuDto;
import com.angel.bo.beans.admin.entity.Menu;
import com.angel.bo.cache.annotation.DictParam;
import com.angel.bo.cache.annotation.TranslationDict;
import com.angel.bo.common.msg.WebReturn;
import com.angel.bo.common.service.impl.BaseServiceImpl;
import com.xiaoleilu.hutool.bean.copier.CopyOptions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 
 *
 * @author ${author}
 * @email haibo.mei@ge.com
 * @date 2018-02-01 14:32:20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MenuServiceImpl extends BaseServiceImpl<MenuMapper,Menu> implements MenuService {


    /**
     * 获取菜单列表
     *
     * @param menu
     * @return
     */
    @Override
    @TranslationDict({@DictParam(dictCode = "MENU_TYPE",dictValueFiled = "menuType",dictNameFiled = "menuTypeName"),
            @DictParam(dictCode = "MENU_STATE",dictValueFiled = "menuState",dictNameFiled = "menuStateName")})
    public WebReturn<MenuDto> getMenuList(Menu menu) {

        List<Menu> menus = super.selectListAll();
        ArrayList<MenuDto> treeMenus = new ArrayList<>();
        for (Menu mu : menus) {
            MenuDto menuDto = new MenuDto();
            com.xiaoleilu.hutool.bean.BeanUtil.copyProperties(mu,menuDto, CopyOptions.create().setEditable(Menu.class));
            treeMenus.add(menuDto);
        }

        ArrayList<MenuDto> treeList = new ArrayList<>();
        for (MenuDto treeMenu : treeMenus) {
            if(treeMenu.getMenuParentId() != null){
                continue;
            }
            MenuDto menuDto = findChildren(treeMenu,treeMenus);
            if(menuDto.getMenuParentId() == null){
                treeList.add(menuDto);
            }

        }
        WebReturn webReturn = new WebReturn();
        webReturn.setData(treeList);

        return webReturn;
    }

    private MenuDto findChildren(MenuDto menuDto, List<MenuDto> treeMenus){

        for (MenuDto treeMenu : treeMenus) {
            if(menuDto.getMenuId().equals(treeMenu.getMenuParentId())){
                treeMenu.setPrentMenuName(menuDto.getMenuName());
                if(menuDto.getChildren() == null){
                    menuDto.setChildren(new ArrayList<MenuDto>());
                }
                menuDto.getChildren().add(findChildren(treeMenu,treeMenus));
            }
        }

        return menuDto;
    }

}



